document.addEventListener('DOMContentLoaded', () => {
    const bookmarkList = document.getElementById('bookmarkList');
    const searchInput = document.getElementById('searchInput');
    const folderNav = document.getElementById('folderNav');
    let allBookmarks = [];

    // Get bookmarks
    chrome.bookmarks.getTree((bookmarkTreeNodes) => {
        // Get top-level folders from the bookmark bar
        const topLevelFolders = bookmarkTreeNodes[0].children[0].children.filter(
            node => node.children
        );

        allBookmarks = processBookmarks(topLevelFolders);
        renderFolders(allBookmarks);
        // 加载保存的选中的目录，如果没有则默认显示第一个目录
        const savedFolderTitle = localStorage.getItem('selectedFolder');
        const folderToRender = savedFolderTitle ? allBookmarks.find(f => f.title === savedFolderTitle) : allBookmarks[0];
        renderBookmarks(folderToRender);
    });

    // Process bookmarks into a structured format
    function processBookmarks(folders) {
        return folders.map(folder => ({
            title: folder.title,
            children: folder.children.filter(child => child.children).map(subfolder => ({
                title: subfolder.title,
                bookmarks: subfolder.children.filter(child => !child.children).map(bookmark => ({
                    title: bookmark.title,
                    url: bookmark.url
                }))
            })),
            bookmarks: folder.children.filter(child => !child.children).map(bookmark => ({
                title: bookmark.title,
                url: bookmark.url
            }))
        }));
    }

    function getFaviconUrl(pageUrl, size = 64) {
        const url = new URL(`chrome-extension://${chrome.runtime.id}/_favicon/`);
        url.searchParams.append("pageUrl", pageUrl);
        url.searchParams.append("size", size.toString());
        return url.href;
    }

    // Render folders to the sidebar
    function renderFolders(folders) {
        folderNav.innerHTML = folders.map(folder => `
      <li class="folder-item" data-title="${folder.title}">
        ${folder.title}
      </li>
    `).join('');

        // Add click event listener to each folder item
        const folderItems = document.querySelectorAll('.folder-item');
        folderItems.forEach(item => {
            item.addEventListener('click', () => {
                folderItems.forEach(i => i.classList.remove('active'));
                item.classList.add('active');
                const folderTitle = item.getAttribute('data-title');
                const folder = allBookmarks.find(f => f.title === folderTitle);
                renderBookmarks(folder);
                // 保存选中的目录
                localStorage.setItem('selectedFolder', folderTitle);
            });
        });

        // 设置默认选中的目录
        const savedFolderTitle = localStorage.getItem('selectedFolder');
        if (savedFolderTitle) {
            const activeFolderItem = document.querySelector(`.folder-item[data-title="${savedFolderTitle}"]`);
            if (activeFolderItem) {
                activeFolderItem.classList.add('active');
            }
        } else {
            const firstFolderItem = document.querySelector('.folder-item');
            if (firstFolderItem) {
                firstFolderItem.classList.add('active');
            }
        }
    }

    // Render bookmarks to the page
    function renderBookmarks(folder) {
        if (!folder) {
            bookmarkList.innerHTML = '<p>暂无书签</p>';
            return;
        }

        bookmarkList.innerHTML = `
      <div class="folder">
        <h2 class="folder-title">${folder.title}</h2>
        <div class="bookmark-list">
          ${renderBookmarkItems(folder.bookmarks)}
        </div>
      </div>
       ${(folder.children || []).map(subfolder => `
            <div class="subfolder">
              <h3 class="subfolder-title">${subfolder.title}</h3>
              <div class="bookmark-list">
                ${renderBookmarkItems(subfolder.bookmarks)}
              </div>
            </div>
          `).join('')}
    `;
    }

    function renderBookmarkItems(bookmarks) {
        return bookmarks.map(bookmark => `
    <div class="bookmark-item">
      <a href="${bookmark.url}" class="bookmark-link" title="${bookmark.title}">
        <img src="${getFaviconUrl(bookmark.url)}" alt="" class="bookmark-favicon">
        ${bookmark.title.length > 12 ? bookmark.title.substring(0, 12) + '...' : bookmark.title}
      </a>
      <div class="bookmark-actions">
        <button class="edit-bookmark" data-url="${bookmark.url}" data-title="${bookmark.title}" title="Edit">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
            <use xlink:href="icons.svg#edit"></use> <!-- 引用外部SVG文件中的编辑图标 -->
          </svg>
        </button>
        <button class="delete-bookmark" data-url="${bookmark.url}" title="Delete">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#ff0000" width="18" height="18">
            <use xlink:href="icons.svg#delete"></use> <!-- 引用外部SVG文件中的删除图标 -->
          </svg>
        </button>
      </div>
    </div>
  `).join('');
    }

    // Theme selector
    const themeSelect = document.getElementById('theme');
    themeSelect.addEventListener('change', () => {
        const selectedTheme = themeSelect.value;
        if (selectedTheme === 'system') {
            setThemeBasedOnPreference();
        } else {
            document.body.setAttribute('data-theme', selectedTheme);
        }
        // 保存选中的主题
        localStorage.setItem('selectedTheme', selectedTheme);
    });

    // Set theme based on browser preference
    function setThemeBasedOnPreference() {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.body.setAttribute('data-theme', 'dark');
        } else {
            document.body.setAttribute('data-theme', 'light');
        }
    }

    // Initial theme setup
    function initializeTheme() {
        // 加载保存的主题，如果没有则使用系统主题
        const savedTheme = localStorage.getItem('selectedTheme');
        if (savedTheme) {
            document.body.setAttribute('data-theme', savedTheme);
            themeSelect.value = savedTheme;
            if (savedTheme === 'system') {
                setThemeBasedOnPreference();
            }
        } else {
            setThemeBasedOnPreference();
        }
    }

    initializeTheme();

    // Listen for changes in theme preference
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (event) => {
        if (themeSelect.value === 'system') {
            setThemeBasedOnPreference();
        }
    });

    // Search functionality
    searchInput.addEventListener('input', (e) => {
        const searchTerm = e.target.value.toLowerCase();

        const filteredBookmarks = allBookmarks.map(folder => ({
            title: folder.title,
            bookmarks: folder.bookmarks.filter(bookmark =>
                bookmark.title.toLowerCase().includes(searchTerm) ||
                bookmark.url.toLowerCase().includes(searchTerm)
            ),
            children: folder.children.map(subfolder => ({
                title: subfolder.title,
                bookmarks: subfolder.bookmarks.filter(bookmark =>
                    bookmark.title.toLowerCase().includes(searchTerm) ||
                    bookmark.url.toLowerCase().includes(searchTerm)
                )
            })).filter(subfolder => subfolder.bookmarks.length > 0)
        })).filter(folder => folder.bookmarks.length > 0 || folder.children.length > 0);

        // If search results are empty, show a message
        if (filteredBookmarks.length === 0) {
            bookmarkList.innerHTML = '<p>No bookmarks found</p>';
            return;
        }

        // Render the filtered bookmarks
        bookmarkList.innerHTML = filteredBookmarks.map(folder => `
      <div class="folder">
        <h2 class="folder-title">${folder.title}</h2>
        <div class="bookmark-list">
          ${renderBookmarkItems(folder.bookmarks)}
        </div>
      </div>
       ${folder.children.map(subfolder => `
            <div class="subfolder">
              <h3 class="subfolder-title">${subfolder.title}</h3>
              <div class="bookmark-list">
                ${renderBookmarkItems(subfolder.bookmarks)}
              </div>
            </div>
          `).join('')}
    `).join('');
    });

    // Edit bookmark
    document.addEventListener('click', (event) => {
        if (event.target.classList.contains('edit-bookmark') || event.target.closest('.edit-bookmark')) {
            const button = event.target.closest('.edit-bookmark');
            const url = button.getAttribute('data-url');
            const title = button.getAttribute('data-title');
            const faviconUrl = getFaviconUrl(url);

            // 创建自定义弹出窗口
            const modal = document.createElement('div');
            modal.className = 'bookmark-modal';
            modal.innerHTML = `
                <div class="modal-content">
                    <span class="close-button">&times;</span>
                    <img src="${faviconUrl}" alt="Bookmark Icon" class="bookmark-favicon">
                    <input type="text" id="edit-title" value="${title}" placeholder="Bookmark Title">
                    <input type="text" id="edit-url" value="${url}" placeholder="Bookmark URL">
                  <div class="modal-buttons">
                    <button id="cancel-changes">取消</button>
                    <button id="save-changes">保存</button>
                 </div>
                </div>
            `;
            document.body.appendChild(modal);

            // 添加遮罩层
            const overlay = document.createElement('div');
            overlay.className = 'modal-overlay';
            document.body.appendChild(overlay);

            // 关闭弹出窗口
            const closeButton = modal.querySelector('.close-button');
            closeButton.addEventListener('click', () => {
                document.body.removeChild(modal);
                document.body.removeChild(overlay);
            });

            // 保存更改
            const saveButton = modal.querySelector('#save-changes');
            saveButton.addEventListener('click', () => {
                const newTitle = document.getElementById('edit-title').value;
                const newUrl = document.getElementById('edit-url').value;
                if (newTitle && newUrl) {
                    chrome.bookmarks.search({url: url}, (results) => {
                        if (results.length > 0) {
                            chrome.bookmarks.update(results[0].id, {title: newTitle, url: newUrl}, () => {
                                const bookmarkItem = button.closest('.bookmark-item');
                                const bookmarkLink = bookmarkItem.querySelector('.bookmark-link');
                                const textNode = document.createTextNode(newTitle.length > 12 ? newTitle.substring(0, 12) + '...' : newTitle);
                                // 删除旧的文本节点
                                bookmarkLink.childNodes.forEach(node => {
                                    if (node.nodeType === Node.TEXT_NODE) {
                                        bookmarkLink.removeChild(node);
                                    }
                                });
                                // 插入新的文本节点
                                bookmarkLink.appendChild(textNode);
                                bookmarkLink.setAttribute('title', newTitle);
                                bookmarkLink.setAttribute('href', newUrl);
                                button.setAttribute('data-title', newTitle);
                                button.setAttribute('data-url', newUrl);
                                // 更新书签的图标
                                const favicon = bookmarkItem.querySelector('.bookmark-favicon');
                                favicon.src = getFaviconUrl(newUrl);
                            });
                        }
                    });
                    document.body.removeChild(modal);
                    document.body.removeChild(overlay);
                }
            });

            // 取消更改
            const cancelButton = modal.querySelector('#cancel-changes');
            cancelButton.addEventListener('click', () => {
                document.body.removeChild(modal);
                document.body.removeChild(overlay);
            });
        }
    });

    // Delete bookmark
    document.addEventListener('click', (event) => {
        if (event.target.classList.contains('delete-bookmark') || event.target.closest('.delete-bookmark')) {
            const button = event.target.closest('.delete-bookmark');
            const url = button.getAttribute('data-url');
            if (confirm('确认删除?')) {
                chrome.bookmarks.search({url: url}, (results) => {
                    if (results.length > 0) {
                        chrome.bookmarks.remove(results[0].id, () => {
                            // 删除书签后重新渲染书签列表
                            const folderTitle = localStorage.getItem('selectedFolder');
                            const folder = allBookmarks.find(f => f.title === folderTitle);
                            // 更新 allBookmarks 数组
                            if (folder) {
                                // 删除书签
                                folder.bookmarks = folder.bookmarks.filter(bookmark => bookmark.url !== url);
                                // 删除子文件夹中的书签
                                folder.children = folder.children.map(subfolder => ({
                                    ...subfolder,
                                    bookmarks: subfolder.bookmarks.filter(bookmark => bookmark.url !== url)
                                }));
                            }
                            renderBookmarks(folder);
                        });
                    }
                });
            }
        }
    });
});